from flask import request, abort, current_app
from flask_login import login_user
import jwt
import six

import datetime

from api.resource import APIView
from api.model.test_model import UserDO


class LoginView(APIView):
    """
    Handles user login.
    """

    url_prefix = ("/login",)

    # def post(self):
    def get(self):
        """
        Handles user login.
        """
        # username = request.values.get("username") or request.values.get("email")
        # password = request.values.get("password")

        username = request.args.get("username") or request.args.get("email")
        password = request.args.get("password")

        logined_user, authenticated = UserDO.query.authenticate(username, password)
        if not authenticated:
            return abort(401, "invalid username or password")
        
        login_user(logined_user)

        token = jwt.encode({
            'sub': logined_user.username,
            'iat': datetime.datetime.now(),
            'exp': datetime.datetime.now() + datetime.timedelta(minutes=24 * 60 * 7)},
            current_app.config['SECRET_KEY'])

        return self.jsonify(token=token.decode() if six.PY2 else token, username=username)
